package com.rainbow.gwt.accounting.server;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rainbow.gwt.accounting.client.UserDescService;
import com.rainbow.gwt.accounting.client.entity.UserDesc;
import com.rainbow.gwt.accounting.server.pojo.User;
import com.rainbow.gwt.accounting.server.util.HibernateUtil;

public class UserDescServiceImpl extends RemoteServiceServlet implements
		UserDescService {

	private static final long serialVersionUID = 1L;

	public UserDesc getUserDesc(String username) {
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<UserDesc> getUserDescs() {
		Session session = null;
		List<User> list = new ArrayList<User>();
		try {
			session = HibernateUtil.currentSession();
			Query query = session.createQuery("from User");
			list = (List<User>)query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally{
			HibernateUtil.closeSession();
		}
		List<UserDesc> allUsers = new ArrayList<UserDesc>();
		for(User user : list){
			UserDesc userDesc = new UserDesc();
			userDesc.setUsername(user.getUsername());
			userDesc.setBirthday(new SimpleDateFormat("yyyy-mm-dd").format(user.getBirthday()));
			userDesc.setCellphone(user.getCellphone());
			userDesc.setSex(user.getSex());
			userDesc.setAddress(user.getAddress());
			allUsers.add(userDesc);
		}
		return allUsers;
	}

	public void setUserDesc(UserDesc userDesc) {
		Session session = null;
		Transaction tx = null;
		User user = new User();
		user.setUsername(userDesc.getUsername());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
		Date birthday = null;
		try {
			birthday = format.parse(userDesc.getBirthday());
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		user.setBirthday(birthday);
		user.setSex(userDesc.getSex());
		user.setCellphone(userDesc.getCellphone());
		user.setAddress(userDesc.getAddress());
		try {
			session = HibernateUtil.currentSession();
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			throw e;
		} finally{
			if(tx != null)
			{
				tx.rollback();
			}
			HibernateUtil.closeSession();
		}
		
	}

}
